# GF_PY3_FLASK3_Document_Plagiarism_Check.py
# Create by GF 2025-04-21

# Python 3 Standard Libraries.
import io
import os
import uuid
# ..................................................
import flask
# ..................................................
import GF_PY3_WORKFLOW_Document_Plagiarism_Check

# ##################################################

app = flask.Flask(__name__)

# ##################################################

# 配置上传和临时结果文件夹
UPLOAD_FOLDER = "D:\\uploads"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 确保上传和临时结果文件夹存在 (不存在则创建)
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# 设置文件大小限制 (例如 16 MB = 16 * 1024 * 1024)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

# ##################################################

@app.route('/api/document-plagiarism-check', methods=['POST'])
def PUSH_POST_API_Document_Plagiarism_Check():

    # Example:
    # - curl -X POST \
    # -      -F "file=@/root/example.docx" http://localhost:5000/api/document-plagiarism-check
    # -      --output result.xlsx
    # Returns:
    # - document_plagiarism_check_result.xlsx

    if 'file' not in flask.request.files:  # 检查请求中是否存在 "文件部分"
        return {'Error': 'No File Uploaded'}, 400

    Uploaded_File = flask.request.files['file']
    # ..............................................
    print("[Message] Document Plagiarism Check -> File: %s Uploaded Successfully" % Uploaded_File.filename)

    if Uploaded_File.filename == '':  # 检查文件名是否为空 (Empty)
        return {'Error': 'No Selected File'}, 400

    # 使用 uuid 生成唯一文件名防止文件名冲突
    # ..............................................
    # file_id = uuid.uuid4().hex
    # Full_Upload_Path = os.path.join(app.config['UPLOAD_FOLDER'], file_id)
    Full_Upload_Path = os.path.join(app.config['UPLOAD_FOLDER'], Uploaded_File.filename)
    Uploaded_File.save(Full_Upload_Path)

    try:

        DPC = GF_PY3_WORKFLOW_Document_Plagiarism_Check.Document_Plagiarism_Check()

        # 调用文档查重函数
        Results_Save_Path = f"{UPLOAD_FOLDER}\\document_plagiarism_check_result.xlsx"
        Execution_Results = DPC.Workflow(Full_Upload_Path, Results_Save_Path)

        # 读取生成的 Excel 文件到内存
        with open(Results_Save_Path, 'rb') as f:
            result_data = io.BytesIO(f.read())

        return flask.send_file(  # 返检测结果 (Excel 格式) 文件
            result_data,
            mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            as_attachment=True,
            download_name="document_plagiarism_check_result.xlsx"
        )

    except Exception as e:

        return {'error': str(e)}, 500

    finally:

        if os.path.exists(Full_Upload_Path):
            os.remove(Full_Upload_Path)  # 如果文件已上传, 则清理文件

        if 'Results_Save_Path' in locals() and os.path.exists(Results_Save_Path):
            os.remove(Results_Save_Path)  # 结果文件已发送给用户, 则清理文件

if __name__ == '__main__':

    app.run(debug=True)

# EOF Signed by GF.
